﻿/******************************************************************************
    myBoard is a port of MacOS X dashboard application for windows.
    Copyright (C) 2007,2008  by Yann ALET
    Email : yann.alet@gmail.com

    myBoard is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    myBoard is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Text;
using myBoard.Framework;
using System.Windows;
using myBoard.Tools;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Media;
using System.Windows.Interop;
using System.Windows.Shapes;
using ShaderEffects;
using System.Windows.Threading;
using myBoard.App.Controllers;

namespace myBoard.App
{
    public partial class Main
    {
        private ScaleEffect _lastShader;
        private bool _isBusyAnimating;
        private bool _initializing;


        /// <summary>
        /// Show magnets in myBoard
        /// </summary>

        public void ShowMagnets()
        {
            if (_activeMagnets == null || _isBusyAnimating)
                return;

            _isBusyAnimating = true;

            //We notify all magnets that we are about to show myBoard
            foreach (MagnetEx magnet in _activeMagnets)
            {
                magnet.Freeze();
                if (magnet.Magnet is IMagnetEvents)
                {
                    IMagnetEvents m = magnet.Magnet as IMagnetEvents;
                    m.OnMyBoardShow();
                }
            }

            int index = 1;
            foreach (MagnetEx magnet in _activeMagnets)
            {
                if (!_magnetsContainer.Children.Contains(((UIElement)magnet.Magnet)))
                    AddMagnet(magnet);                    
                
                index++;
            }
            
            if (_lastShader == null)
            {
                _lastShader = new ScaleEffect();
                _lastShader.ScaleFactor = 6;
            }
            
            var scaleTimeline = new DoubleAnimationUsingKeyFrames();
            scaleTimeline.KeyFrames.Add(new SplineDoubleKeyFrame(_lastShader.ScaleFactor, KeyTime.FromPercent(0)));
            scaleTimeline.KeyFrames.Add(new SplineDoubleKeyFrame(1, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 400)), new KeySpline(0,1,1,1)));
            
            if (_root.Effect == null)
            {
                _root.Effect = _lastShader;
                _root.Opacity = 1;
            }
            scaleTimeline.Completed += new EventHandler(ShowMagnetsCompleted); 
            _root.Effect.BeginAnimation(ScaleEffect.ScaleFactorProperty, scaleTimeline);
        }

        /// <summary>
        /// Hides magnets
        /// </summary>

        public void HideMagnets()
        {
            HideMagnets(null);
        }

        public void HideMagnets(EventHandler callback)
        {
            if (_activeMagnets == null || _isBusyAnimating)
            {
                return;
            }
            _isBusyAnimating = true;
            //We notify all magnets that we are about to hide myBoard
            foreach (MagnetEx magnet in _activeMagnets)
            {
                magnet.Freeze();
                if (magnet.Magnet is IMagnetEvents)
                {
                    IMagnetEvents m = magnet.Magnet as IMagnetEvents;
                    m.OnMyBoardHide();
                }
            }

            if (_lastShader == null)
                _lastShader = new ScaleEffect();

            var scaleTimeline = new DoubleAnimationUsingKeyFrames();
            scaleTimeline.KeyFrames.Add(new SplineDoubleKeyFrame(_lastShader.ScaleFactor, KeyTime.FromPercent(0)));
            scaleTimeline.KeyFrames.Add(new SplineDoubleKeyFrame(16, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 400)), new KeySpline(1, 0, 1, 1)));

            _root.Effect = _lastShader;
            if (callback != null)
            {
                scaleTimeline.Completed += callback;                
            }

            scaleTimeline.Completed += new EventHandler(delegate(object sender, EventArgs e)
            {
                _root.Effect = null;
                _root.Opacity = 0;
                foreach (MagnetEx magnet in _activeMagnets)
                {
                    magnet.UnFreeze();
                    if (magnet.Magnet is IMagnetEvents)
                    {
                        IMagnetEvents m = magnet.Magnet as IMagnetEvents;
                        m.OnMyBoardHideCompleted();
                    }
                }
                _isBusyAnimating = false;
            });

            _root.Effect.BeginAnimation(ScaleEffect.ScaleFactorProperty, scaleTimeline);
        }

        

        void ShowMagnetsCompleted(object sender, EventArgs e)
        {
            //Leaving pixel shaders on _root decrease global performance, so we remove it after the animation
            _root.Effect = null;

            foreach (MagnetEx magnet in _activeMagnets)
            {
                magnet.UnFreeze();
                if (magnet.Magnet is IMagnetEvents)
                {
                    IMagnetEvents m = magnet.Magnet as IMagnetEvents;
                    m.OnMyBoardShowCompleted();
                }
            }
            _isBusyAnimating = false;
            if (_initializing)
            {
                HideMagnets();
                _initializing = false;
            }
        }

        /// <summary>
        /// This brings myBoard on screen
        /// </summary>

        public void ShowMyBoard()
        {
            this.Topmost = true;
            if ((Environment.OSVersion.Version.Major >= 6) && Tools.DwmApi.DwmIsCompositionEnabled())
            {
                WindowInteropHelper helper = new WindowInteropHelper(this);
                base.Background = Brushes.Transparent;
                HwndSource.FromHwnd(helper.Handle).CompositionTarget.BackgroundColor = Colors.Transparent;
                Tools.DwmApi.DwmExtendFrameIntoClientArea(helper.Handle, new Tools.DwmApi.MARGINS(-1, -1, -1, -1));
            }
            
            _currentlyDraggedMagnet = null;
            this.Top = 0;
            Storyboard s = this.FindResource("Intro") as Storyboard;
            if (s != null)
                this.BeginStoryboard(s);
            _activated = true;            

        }

        /// <summary>
        /// This hides myBoard with a fade out and move it offscreen
        /// </summary>

        public void HideMyBoard()
        {
            Storyboard s = this.FindResource("Outro") as Storyboard;
            if (s != null)
            {
                s.Completed += new EventHandler(delegate
                {
                    this.Top = System.Windows.SystemParameters.PrimaryScreenHeight;
                    MainController.ReleaseUnusedMemory();
                });
                this.BeginStoryboard(s);
            }
            _activated = false;
            this.Topmost = false;
        }

        void HideShowLibBut_Click(object sender, RoutedEventArgs e)
        {
            if (_magnetsContainer.Margin.Top == 0)
            {
                Storyboard s = this.FindResource("ShowLocalMagnetsLibrary") as Storyboard;
                
                //Ugly !
                /*s.Completed += delegate(object sb_sender, EventArgs sb_e)
                {
                    //Make a screen capture just in case we need to do the ripple effect
                    Screen screen = new Screen();
                    _fakeBgImage.Visibility = Visibility.Hidden;
                    _fakeBgImage.Source = screen.Capture();
                };*/

                if (s != null)
                    this.BeginStoryboard(s);
                _localMagnetsExplorer.ExtendLibrary();
            }
            else
            {
                Storyboard s = this.FindResource("HideLocalMagnetsLibrary") as Storyboard;
                if (s != null)
                    this.BeginStoryboard(s);
                _localMagnetsExplorer.RetractLibrary();
            }
        }
    }
}
